﻿package {
	import flash.external.ExternalInterface;
	
	// Flash与JavaScript交互实现
	public class Active {
		public var jsMethod:Object;
		
		public function Active() {
			jsMethod = {};
		}
		
		private function loadJsMethod(methodName:String):Function {
			return function(arg:Object = null) {
				return ExternalInterface.call(methodName, arg);
			}
		}
		
		/**
		 * 載入外部的JS函數/類
		 * @param {Object} api 要載入的api，鍵名為AS中調用的值，鍵值為實際的JS函數/方法名
		 */
		public function loadJSAPI(api:Object):void {
			for (var p: String in api) {
				jsMethod[p] = loadJsMethod(api[p]);
			}
		}
		
		/**
		 * 將AS中的方法發佈至WEB流覽器供JS調用
		 * @param {Object} api 要發佈的API，鍵名為JS中所調用的名稱，鍵值為AS中實際的方法名稱
		 */
		public function publishASAPI(api:Object):void {
			for (var p:String in api) {
				ExternalInterface.addCallback(p, api[p]);
			}
		}
	}
	
	/**
	示例：
	
	AS代碼：
	class Test extends Sprite {
		private var msgText: String;
		public function Test() {
			private var active: Active = new Active();
			active.loadJSAPI({ requestData : 'upload' });
			active.publishASAPI({ setASMsg : setMsg });
			
			// 調用JS中的upload方法
			active.jsMethod.requestData('ly');
		}
		
		public function setMsg(msg: String): void {
			msgText = msg;
		}
	}
	
	JS代碼：
	<script type="text/javascript">
	// <![CDATA[
		
		function upload(name) {
			// flashObj為頁面中的FLASH對象，即Object/Embed對象
			flashObj.setASmsg(name);
		}
		
	// ]]>
	</script>
	 */
}